package pool;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;

// 建立DBConnectionPool内部类
class DBConnectionPool {
	private PrintWriter log;
	private int checkOut;
	private Vector freeConnections = new Vector();
	private int maxconn;
	private String name;
	private String password;
	private String URL;
	private String user;

	public DBConnectionPool(String name, String URL, String user,
			String password, int maxconn) {
		this.name = name;
		this.URL = URL;
		this.password = password;
		this.user = user;
		this.maxconn = maxconn;
	}
//放入连接池
	public synchronized void freeConnection(Connection con) {
		freeConnections.addElement(con);
		checkOut--;
		notifyAll();
	}
//获取连接
	public synchronized Connection getConnection() {
		Connection con = null;
		//在连接池有连接时，从里面取连接
		if (freeConnections.size() > 0) {
			con = (Connection) freeConnections.firstElement();
			freeConnections.removeElementAt(0);
			try {
				if (con.isClosed()) {
					log("从连接池" + name + "删除一个连接");
					con = getConnection();
				}
			} catch (SQLException e) {
				log("从连接池" + name + "删除一个连接");
				con = getConnection();
			}
		} else if (maxconn == 0 || checkOut < maxconn) {
			con = newConnection();
		}
		if (con != null) {
			checkOut++;
		}
		return con;
	}

	//
	public synchronized Connection getConnection(long timeout) {
		long startTime = new Date().getTime();
		Connection con;
		while ((con = getConnection()) == null) {
			try {
				wait(timeout);
			} catch (InterruptedException e) {
			}
			if ((new Date().getTime() - startTime) >= timeout) {
				return null;
			}
		}
		return con;
	}

	//连接池释放所有连接
	public void release() {
		Enumeration allConnections = freeConnections.elements();
		while (allConnections.hasMoreElements()) {
			Connection con = (Connection) allConnections.nextElement();
			try {
				con.close();
				log("关闭连接池" + name + "中的连接");
			} catch (SQLException e) {
				log(e, "无法关闭连接池" + name + "中的连接");
			}
		}
		freeConnections.removeAllElements();
	}
//new 一个出来
	private Connection newConnection() {
		Connection con = null;
		try {
			con = DriverManager.getConnection(URL, user, password);
			log("连接池" + name + "创建一个新的连接");
		} catch (SQLException e) {
			log(e, "无法创建下列URL的连接" + URL);
			return null;
		}
		return con;
	}
	
	
	
	private void log(String msg) {
		log.println(new Date() + ":" + msg);
	}

	private void log(Throwable e, String msg) {
		log.println(new Date() + ":" + msg);
		e.printStackTrace(log);
	}
}